package com.lzw.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 *
 */
@Slf4j
public class JsonUtils {

    private static final ObjectMapper MAPPER = new ObjectMapper();

    static {
        //反序列化，若实体类没有对应的属性，是否抛出异常  false-否
        MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        //忽略空属性
        MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        MAPPER.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
        MAPPER.enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS);
    }

    public static ObjectMapper getMapper() {
        return MAPPER;
    }

    /**
     * 对象转JSON
     *
     * @param o Object
     * @return json
     */
    public static String toJson(Object o) {
        try {
            return MAPPER.writeValueAsString(o);
        } catch (JsonProcessingException e) {
            log.debug("", e);
        }
        return null;
    }

    /**
     * JSON转对象
     *
     * @param json  json
     * @param clazz 对象
     * @param <T>   <T>
     * @return <T>
     */
    public static <T> T toBean(String json, Class<T> clazz) {
        try {
            return MAPPER.readValue(json, clazz);
        } catch (IOException e) {
            log.debug("", e);
        }
        return null;
    }

    /**
     * JSON转对象
     *
     * @param json  json
     * @param clazz class
     * @param cla   泛型class
     * @return clazz<cla>
     */
    public static Object toBean(String json, Class<?> clazz, Class<?> cla) {
        try {
            JavaType javaType = MAPPER.getTypeFactory().constructParametricType(clazz, cla);
            return MAPPER.readValue(json, javaType);
        } catch (IOException e) {
            log.debug("", e);
        }
        return null;
    }
}
